package com.jiaoxn.example.common.validate;

import com.jiaoxn.example.common.response.structure.ResponseStructure;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author jiao xn
 * @date 2022/8/28
 */
@RestControllerAdvice
public class ControllerAdvice {
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ExceptionHandler({BindException.class})
    public ResponseStructure<?> bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();

        return ResponseStructure.failed(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseStructure<?> bindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        return ResponseStructure.failed(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }
}
